<template>
  <div class="my-submit-list">
    <a-form layout="inline">
      <a-form-item label="">
        <a-range-picker
          v-model="queryParam.timeRange"
          :show-time="{ format: 'HH:mm' }"
          format="YYYY-MM-DD HH:mm"
          :placeholder="['开始时间', '结束时间']"
          value-format="YYYY-MM-DD HH:mm:ss"
          @ok="handleTimeRangeChange" />
      </a-form-item>
      <a-form-item label="">
        <a-select v-model="queryParam.approvalStatus" placeholder="审批状态" :style="{ width: '200px' }">
          <a-select-option value="">全部</a-select-option>
          <a-select-option v-for="item in approvalStatusOptions" :key="item.value" :value="item.value">
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="">
        <a-select v-model="queryParam.applyType" placeholder="流程类型" :style="{ width: '200px' }">
          <a-select-option value="">全部</a-select-option>
          <a-select-option v-for="item in applyTypeOptions" :key="item.value" :value="item.value">
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="">
        <a-button type="primary" @click="searchHandle">搜索</a-button>
      </a-form-item>
    </a-form>
    <s-table
      ref="table"
      size="default"
      rowKey="id"
      :columns="columns"
      :data="loadData"
      :alert="false"
      showPagination="auto"
      :pagination="pagination">
      <span slot="operation" slot-scope="text, record">
        <a-button type="link" @click="handleDetail(record)" v-if="$hasPermission('approvalDetail')">审核详情</a-button>
      </span>
    </s-table>
    <a-modal title="审核详情" :visible="visible" @ok="visible = false" @cancel="visible = false" width="800px">
      <div v-if="currentRecord">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="流程编号">{{ currentRecord.id }}</a-descriptions-item>
          <a-descriptions-item label="流程类型">{{ getFlowTypeText(currentRecord.flowType) }}</a-descriptions-item>
          <a-descriptions-item label="模型名称">{{ currentRecord.modelName }}</a-descriptions-item>
          <a-descriptions-item label="提交人">{{ currentRecord.proposer }}</a-descriptions-item>
          <a-descriptions-item label="提交时间">{{ formatTime(currentRecord.applyTime) }}</a-descriptions-item>
          <a-descriptions-item label="审核状态">{{ getStatusText(currentRecord.approvalStatus) }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { STable } from '@/components'
import { applyApprovalByMe } from '@/api/operatorCheck'
import moment from 'moment'

const columns = [
  {
    title: '流程编号',
    dataIndex: 'id',
    width: 80,
  },
  {
    title: '流程类型',
    dataIndex: 'flowType',
    width: 120,
    customRender: (text, record) => {
      const typeMap = {
        '00': 'Python删除',
        '01': 'Python上线',
        '02': 'Python下线',
        10: 'PMML删除',
        11: 'PMML上线',
        12: 'PMML下线',
        20: '评分卡删除',
        21: '评分卡上线',
        22: '评分卡下线',
      }
      return typeMap[text] || ''
    },
  },
  {
    title: '模型名称',
    dataIndex: 'modelName',
    width: 180,
  },
  {
    title: '提交人/提交时间',
    dataIndex: 'applyTime',
    width: 180,
    customRender: (text, record) => {
      return `${record.proposer} ${moment(text).format('YYYY-MM-DD HH:mm:ss')}`
    },
  },
  {
    title: '审核人',
    dataIndex: 'approver',
    width: 120,
  },
  {
    title: '审核状态',
    dataIndex: 'approvalStatus',
    width: 100,
    customRender: (text, record) => {
      const statusMap = {
        0: '审核中',
        1: '审核通过',
        2: '审核不通过',
      }
      return statusMap[text] || '未知状态'
    },
  },
  {
    title: '操作',
    scopedSlots: { customRender: 'operation' },
    width: 100,
    fixed: 'right',
  },
]

export default {
  name: 'MySubmit',
  components: {
    STable,
  },
  data() {
    // 设置默认时间范围：最近30天
    const now = moment()
    const thirtyDaysAgo = moment().subtract(30, 'days')
    const defaultTimeRange = [thirtyDaysAgo.format('YYYY-MM-DD HH:mm:ss'), now.format('YYYY-MM-DD HH:mm:ss')]

    return {
      columns,
      visible: false,
      currentRecord: null,
      pagination: {
        total: 0,
        current: 1,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      // 审批状态选项
      approvalStatusOptions: [
        { value: '0', label: '审核中' },
        { value: '1', label: '审核通过' },
        { value: '2', label: '审核不通过' },
      ],
      // 流程类型选项
      applyTypeOptions: [
        { value: '00', label: 'Python删除' },
        { value: '01', label: 'Python上线' },
        { value: '02', label: 'Python下线' },
        { value: '10', label: 'PMML删除' },
        { value: '11', label: 'PMML上线' },
        { value: '12', label: 'PMML下线' },
        { value: '20', label: '评分卡删除' },
        { value: '21', label: '评分卡上线' },
        { value: '22', label: '评分卡下线' },
      ],
      queryParam: {
        approvalStatus: undefined, // 审批状态0审核中 1审核通过 2审核不通过
        timeRange: defaultTimeRange,
        applyType: undefined,
      },
    }
  },

  methods: {
    handleTableChange(pagination) {
      this.$emit('change', pagination)
    },
    searchHandle() {
      this.$refs.table.refresh(true)
    },
    handleTimeRangeChange(dates, dateStrings) {
      // 当日期范围改变时自动触发查询
      this.searchHandle()
    },
    resetHandle() {
      this.queryParam = {
        approvalStatus: '',
        timeRange: null,
        applyType: '',
      }
      this.$refs.table.refresh(true)
    },
    loadData(parameter) {
      const requestParameters = Object.assign(
        {},
        {
          curPage: parameter.pageNo,
          pageSize: parameter.pageSize,
          applyType: '01', // 流程类型
        },
        this.queryParam
      )

      // 处理时间范围参数
      if (requestParameters.timeRange && requestParameters.timeRange.length) {
        requestParameters.startTime = moment(requestParameters.timeRange[0]).unix() * 1000
        requestParameters.endTime = moment(requestParameters.timeRange[1]).unix() * 1000
        delete requestParameters.timeRange
      }

      console.log('loadData request parameters:', requestParameters)

      return applyApprovalByMe(requestParameters).then((res) => {
        if (res.success && res.data) {
          // 转换数据格式以匹配表格显示
          const processedData = res.data.processData.map((item) => ({
            id: item.id,
            flowType: item.applyType,
            modelName: `${item.name}.${item.version}`,
            proposer: item.proposer,
            applyTime: item.applyTime,
            approver: item.approver,
            approvalStatus: item.approvalStatus,
            applyReasons: item.applyReasons,
            approvalReasons: item.approvalReasons,
            approvalTime: item.approvalTime,
            modelUuid: item.modelUuid,
          }))

          return {
            ...res.data,
            data: processedData || [],
          }
        }
        return {
          total: 0,
          curPage: 1,
          totalPage: 0,
          pageSize: 10,
          data: [],
        }
      })
    },
    handleDetail(record) {
      this.$router.push({
        path: '/model/checkOperation/myCheckedDetail',
        query: {
          approvalId: record.id,
          source: 'mySubmit' // 标识来源为我提交的tab
        }
      })
    },

    getFlowTypeText(type) {
      const typeMap = {
        '00': 'Python删除',
        '01': 'Python上线',
        '02': 'Python下线',
        10: 'PMML删除',
        11: 'PMML上线',
        12: 'PMML下线',
        20: '评分卡删除',
        21: '评分卡上线',
        22: '评分卡下线',
      }
      return typeMap[type] || ''
    },
    getStatusText(status) {
      const statusMap = {
        0: '审核中',
        1: '审核通过',
        2: '审核不通过',
      }
      return statusMap[status] || ''
    },
    formatTime(time) {
      return moment(time).format('YYYY-MM-DD HH:mm:ss')
    },
    setQuickDate(type) {
      const now = moment()
      let startTime, endTime

      switch (type) {
        case 'today':
          startTime = now.clone().startOf('day')
          endTime = now.clone().endOf('day')
          break
        case 'week':
          startTime = now.clone().startOf('week')
          endTime = now.clone().endOf('week')
          break
        case 'month':
          startTime = now.clone().startOf('month')
          endTime = now.clone().endOf('month')
          break
        default:
          return
      }

      this.queryParam.timeRange = [startTime.format('YYYY-MM-DD HH:mm:ss'), endTime.format('YYYY-MM-DD HH:mm:ss')]

      // 自动触发搜索
      this.searchHandle()
    },
  },
}
</script>

<style lang="less" scoped>
.my-submit-list {
  .ant-form {
    margin-bottom: 16px;
  }
}
</style>
